//
//  GoodsSearchCtr.swift
//  smosky
//
//  Created by zhu xietong on 2018/5/18.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import soapp
import Eelay
import AsyncDisplayKit

fileprivate var __history:SearchHistory? = nil
extension SearchHistory{
    public static var shopping:SearchHistory{
        get{
            if let obj = __history{
                return obj
            }
            let newObj = SearchHistory()
            newObj.historyType = "shopping"
            __history = newObj
            return newObj
        }
    }    
}

class Eeconfig: ASColDataSource {
    override func collectionNode(_ collectionNode: ASCollectionNode, nodeForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> ASCellNode {
        return GoodsSearchCtr.Header()
    }
    
    override func collectionNode(_ collectionNode: ASCollectionNode, numberOfItemsInSection section: Int) -> Int {
        return super.collectionNode(collectionNode, numberOfItemsInSection: section)
    }
}


open class GoodsSearchCtr:EeSearchController{
    public var filter:Goods.Filter = Goods.Filter()
    override open var selector: TP.selector{
        let sec:TP.selector = TP.selector() + Goods.cellSelector
        return sec
    }
    
    override open var searchKey: String{
        set{
            super.searchKey = newValue
        }
        get{
            return super.searchKey
        }
    }
    
    override open func viewDidLoad() {
        self.page_load_section = "section0"
        self.content = ASTermsContainer.list(
            net: JoTask().post._surl(.商品列表).log.log_response(),
            node: "list",
            emptyMsg: "没有相关内容".loc,
            params: nil,
            cellType: Goods.PaiMaiCell.self,
            detailType: Goods.DetailCtrType,
            test: false
        )
        
        collection_config = Eeconfig()
        super.viewDidLoad()
        navBar.searchBar.textBack.bsui.set(radius: 15, width: nil, color: nil)
        self.navBar.searchBar.historyMananger = SearchHistory.shopping
        self.navBar.searchBar.textField.placeholder = "商品搜索".loc
        if let key = filter.searchKey{
            navBar.searchBar.textField.text = key
        }
        paginator.parameters = filter.params
        //
        flowLayout.sectionHeadersPinToVisibleBounds = true
        flowLayout.minimumLineSpacing = Goods.minimumLineSpacing
        flowLayout.minimumInteritemSpacing = Goods.minimumInteritemSpacing
        //        flowLayout.headerReferenceSize = [Swidth,30]
        collectionNode.registerSupplementaryNode(ofKind: UICollectionView.elementKindSectionHeader)
        view.backgroundColor = ._background
        //        collectionNode.view.register(Header.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
        
        //        collectionNode
        //        top_style.navBarBgStyle = .color(UIColor(shex: "#BFBFBF"))
        
        
    }
    
    override open func layCollection(collectionView: UIView) {
        
        
        let item1 = FilterOption()
        item1.filterKey = "type_price"
        item1.button.ui.ntitle(title: "分类  ").stitle(title: "分类  ").nimage(UIImage(named: "shop_order_n")).simage(UIImage(named: "shop_order_s")).scolor(color: ._foreground).ncolor(hex: "#888").font(size: 13).imagePosition(.right)
        item1.filterSelector = .dropView(GoodsCateSelector())
        
        
        let item2 = FilterOrder()
        item2.button.ui.ncolor(hex: "#070707").ntitle(title: "热度".loc).nimage(UIImage(named: "shop_order_n")).simage(UIImage(named: "shop_order_s")).scolor(color: ._foreground).ncolor(hex: "#888").font(size: 13).imagePosition(.right)
        item2.asc = ("热度".loc,"sales","asc",nil)
        //        item2.desc = ("热度  ","time_deliver","-",nil)
        
        
        
        let item3 = FilterOrder()
        item3.button.ui.ntitle(title: "价格".loc).nimage(UIImage(named: "lplb_xiala")).scolor(color: ._foreground).ncolor(hex: "#888").font(size: 13).imagePosition(.right)
        item3.asc = ("价格".loc,"productprice","asc",UIImage(named: "sc_px"))
        item3.desc = ("价格".loc,"productprice","desc",UIImage(named: "sc_px2"))
        
        
        view.backgroundColor = ._background
        menu.cellType = MenuCell.self
        let line = UIView()
        view.eelay = [
            [menu,[ee.T.L.R,[(TP.topHeight),0,0]],"38"],
//            [line,[menu,ee.L.B.R],"\(TP.separatorHeight)"],
            [contentView,[ee.T,(TP.topHeight+38)],[ee.L.B.R]],
        ]
        menu.eelay = [
            [line,[ee.L.B.R],"\(TP.separatorHeight)"]
        ]
        
        line.backgroundColor = ._separator
        
        jo_contentView.eelay = [
            [collectionView,[ee.T],[ee.L.B.R]],
        ]
        
        
        item1.itemWidth = Swidth/3.0
        item2.itemWidth = Swidth/3.0
        item3.itemWidth = Swidth/3.0
        
        menu.collectionViewConfig = {
            cv in
            if let flow = cv.collectionViewLayout as? UICollectionViewFlowLayout
            {
                flow.minimumInteritemSpacing = 0
                flow.minimumLineSpacing = 0
            }
        }
        menu.items = [item1,item2,item3]
        menu.observerFilter = {[weak self] info in
            self?.filterValues = info
        }
        
        menu.menu_height = 38
        menu.controller = self
        menu.backgroundColor = ._background
    }
    
    override open func change(searchKey: String) {
        if searchKey.len > 0
        {
            filterValues = [
                "name":"searchKey",
                "value":searchKey
            ]
        }
        else
        {
            filterValues = [
                "name":"searchKey",
            ]
        }
    }
    
    override open func updateListWith() {
        
        //        print("--=======ss=\(filterValues)")
        let info = self.filterValues.mutable_dictionary
        switch info["name",""] {
        case "cate":
            filter.cate = filterValues["value"] as? [String:Any]
        case "searchKey":
            filter.searchKey = filterValues["value"] as? String
        case "order":
            filter.order = ["order":info["orderKey",""],"by":info["by",""]]
        default:
            break
        }
        paginator.parameters = filter.params
        reload_page()
//        co_delay(delay: 0.25) {[weak self] () in
//            self?.reload_page()
//        }
    }
    
    open override func loadOnePage(list: [Any]) -> [Any] {
        for item in list {
            if let dict = item as? NSMutableDictionary{
                Goods.ActiveType.markCellID(item: dict)
            }
        }
        return list
    }
    
    
    override open func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        __post(notify: Goods.BaseCell.Notice.controllerWillAppear, object: self, userInfo: nil)
    }
    
    override open func viewWillDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        __post(notify: Goods.BaseCell.Notice.controllerDisAppear, object: self, userInfo: nil)
    }
    
    open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return Goods.listInset
    }
}

extension GoodsSearchCtr{
    
    open class Header: JoCellNode {
        let nameN = ASTextNode2()
        override open func addLayoutRules() {
        }
        override open func specGetter() -> _Spec {
            return .inset([], [30], child: nameN["40"])
        }
    }
    class Cell:JoCellNode{
        
        let imgV = JoImageNode()
        let titleL = ASTextNode()
        let infoL = ASTextNode()
        let timeL = ASTextNode()
        
        override func addLayoutRules() {
            
            infoL.maximumNumberOfLines = 1
            self.backgroundColor = ._background
            
            separatorHeight = TP.separatorHeight
            
            
        }
        override func specGetter() -> _Spec {
            return .inset([],[8], child:.stack(["h|10",_shrink(1),_nowrap], childs: [
                imgV["\(90)",120],
                .stack(["V|10",_shrink(1)], childs: [
                    titleL[_shrink(1)],
                    infoL[_shrink(1)]
                    ])
                ]))
        }
        
        override func mo_model_reload() {
            //            print("====UU|\(mo.model)")
            imgV.img_url = mo.model["img",""]
            //            imgV.url = URL(string: mo.model["thumb",""])
            //            imgV.url = URL(string:"http://img4.duitang.com/uploads/blog/201409/06/20140906181244_WAjKB.gif")
            titleL.attributedText = mo.model["title",""].ui.cl_222.bfont16.lineSpace(5).astring
            infoL.attributedText = mo.model["subTitle",""].ui.cl_666.font14.lineSpace(5).astring
        }
        
        
        
    }
}

